package com.ljt.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ljt.security.AccountUser;
import com.ljt.system.entity.User;
import com.ljt.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("userDetailsServiceImpl")
public class UserDetailsServiceImpl implements UserDetailsService{

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",name);
        User user = userService.getOne(queryWrapper);
        System.out.println("user = " + user);
        if(user == null){
            throw new UsernameNotFoundException(String.format("%s这个用户不存在",name));
        }

        return new AccountUser(user.getId(),user.getUsername(),user.getPassword(),getGrantedAuthority(user.getId()));
    }

    public List<GrantedAuthority> getGrantedAuthority(Long id){
        String userAuthorityInfo = userService.getUserAuthorityInfo(id);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(userAuthorityInfo);
    }
}
